﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Text.RegularExpressions;//要用正则表达式要引用


namespace graduation_projects  
{
    public partial class Medicine : Form   
    {   
        int firsttime = 0;  //firsttime作用：比如查找阿莫西林（amxl）时,当输入a,firsttime由0变1，继续输入m,firsttime已经是1，不用再连数据库，继续输入x,firsttime还是1，不用再连数据库
                            //即只连一次数据库
        DataSet ds1;
        string ypdm;
        
        public Medicine()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.Top = 118;
            this.Left = 150;
            skinEngine1.SkinFile = "MSN.ssk";//设置皮肤

            System.Windows.Forms.ToolTip tip1 = new ToolTip(); // 
            tip1.SetToolTip(this.buttonpym, "点击右键选择更多查询条件，点击左键隐藏更多");   //设置鼠标停留在该按钮上时，显示提示信息
            System.Windows.Forms.ToolTip tip2 = new ToolTip(); // 
            tip2.SetToolTip(this.button7, "快捷键:ENTER键");   //设置鼠标停留在该按钮上时，显示提示信息
            System.Windows.Forms.ToolTip tip3 = new ToolTip(); // 
            tip3.SetToolTip(this.buttonmhcx, "快捷键:ENTER键");   //设置鼠标停留在该按钮上时，显示提示信息
            try
            {
                treeView1.ExpandAll();
                treeView1.SelectedNode = treeView1.Nodes[0].FirstNode.FirstNode;//选中“青霉素类”节点
                medicineShow("0101");
            }
            catch(Exception ex)
            {
                MessageBox.Show("error!" + ex.ToString());
            }
        }


        private void setYpdm(int nownodeindex, int parnodeindex, int rootnodeindex)//选中节点为第三层节点时 调用
        {
                ypdm = "0" + Convert.ToString(parnodeindex + 1) + "0" + Convert.ToString(nownodeindex+1);
                medicineShow(ypdm);
            
          
           
        }
        private void setYpdm(int nownodeindex, int parnodeindex)//选中节点为第二层节点时 调用
        {
            ypdm = "0" +Convert.ToString(nownodeindex + 1)+ "01";
            medicineShow(ypdm);
        }
        private void setYpdm(int nownodeindex)//选中节点为第一层节点时 调用
        {
            ypdm = "0101";
            medicineShow(ypdm);
        }
        private void medicineShow(string ypdm) 
        {
            SqlDataAdapter sda = new SqlDataAdapter();
            SqlCommand cmd = new SqlConnection(SQLConnect.get()).CreateCommand();
            cmd.CommandText = "select ypmc as '药品名称',ypgg as '药品规格',ypdw as '药品单位',jixing as '剂型',mzjl as '门诊剂量',jldw as '剂量单位',zxbz as '最小包装',zxdw as '最小单位',zxdj as '最小单价',pydm as '拼音代码',wbdm as '五笔代码',case tsyp when '0' then '普通' when '1' then '特殊' end as '特殊药品',case pishi when '0' then '否' when '1' then '是' end as '皮试'," +
            "case type when '1' then '西药' when '2' then '中药' end as '类型 ',case zfpb when '0' then '否' when '1' then '是' end as '作废',productor as '生产商' from typk where ypdm=@ypdm";
            sda.SelectCommand = cmd;

            SqlParameter para = new SqlParameter("@ypdm", SqlDbType.NVarChar);
            para.Value = ypdm;
            cmd.Parameters.Add(para);

            DataTable dt = new DataTable();
            sda.Fill(dt);
            this.dataGridViewflcx.DataSource = dt;
            dataGridViewflcx.Visible = true;
            dataGridViewmhcx.Visible = false;
            dataGridViewpywb.Visible = false;
        }

       //----------------------------------------------------------------------------------------------------------------

        //textbox有变化，先执行keydown，再执行textchange！！！

        //鼠标选中某个节点 或 键盘上选中某个节点按下回车时 （1）判定节点层次 (2)setYpdm(),设置药品代码 (3)medicineShow（）

        private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)//判定节点
        {
           
            int nownodeindex = e.Node.Index;
            int parnodeindex = 0; ;
            int rootnodeindex=0;
            try
            {

                parnodeindex = e.Node.Parent.Index;
               
            }
            catch
            {
                setYpdm(nownodeindex);//判定出是第一层节点
                return;
            }
            try
            {
                rootnodeindex = e.Node.Parent.Parent.Index;
                
            }
            catch
            {
                setYpdm(nownodeindex, parnodeindex);//判定出是第二层节点
                return;
            }

            setYpdm(nownodeindex, parnodeindex, rootnodeindex);//判定出是第三层节点

        }

        private void treeView1_KeyDown(object sender, KeyEventArgs e)//判定节点，让回车键与用鼠标按下有同样的效果
        {
            if (e.KeyCode == Keys.Enter)
            {
                int now = treeView1.SelectedNode.Index;
                int par = 0;
                int root = 0;
                try
                {

                    par = treeView1.SelectedNode.Parent.Index;

                }
                catch
                {
                    setYpdm(now);//判定出是第一层节点
                    return;
                }
                try
                {
                    root = treeView1.SelectedNode.Parent.Parent.Index;

                }
                catch
                {
                    setYpdm(now, par);//判定出是第二层节点
                    return;
                }

                setYpdm(now, par, root);//判定出是第三层节点

            }

               
            
        }

        //----------------------------------------------------------------------------------------------------

        private void getData()//连接数据库，填充数据到dataset.datatable
        {
            SqlConnection conn = new SqlConnection(SQLConnect.get());
            try
            {
                conn.Open();
                SqlDataAdapter da = new SqlDataAdapter("select ypmc as '药品名称',ypgg as '药品规格',ypdw as '药品单位',jixing as '剂型',mzjl as '门诊剂量',jldw as '剂量单位',zxbz as '最小包装',zxdw as '最小单位',zxdj as '最小单价',pydm as '拼音代码',wbdm as '五笔代码',case tsyp when '0' then '普通' when '1' then '特殊' end as '特殊药品',case pishi when '0' then '否' when '1' then '是' end as '皮试'," +
                "case type when '1' then '西药' when '2' then '中药' end as '类型 ',case zfpb when '0' then '否' when '1' then '是' end as '作废',productor as '生产商' from typk", conn);
                ds1 = new DataSet();
                da.Fill(ds1);
                this.dataGridViewpywb.DataSource = ds1.Tables[0].DefaultView;//读取全部数据，还没过滤的
            }
            catch (Exception ex)
            {
                MessageBox.Show("error!" + ex.ToString());
            }
            finally
            {
                conn.Close();
            }


        }

        private void buttonpym_MouseUp(object sender, MouseEventArgs e)//拼音码的右键事件
        {
            if (e.Button == MouseButtons.Right)
            {
                buttonwbm.Visible = true;
                buttonpy.Visible = true;
                buttonjqcx.Visible = true;
            }
            else
            {
                buttonwbm.Visible = false;
                buttonpy.Visible = false;
                buttonjqcx.Visible = false;
            }
        }

        private void buttonpy_Click(object sender, EventArgs e)//拼音码
        {
            buttonpym.Text = buttonpy.Text;
            buttonwbm.Visible = false;
            buttonpy.Visible = false;
            buttonjqcx.Visible = false;
        }
        private void buttonwbm_Click(object sender, EventArgs e)//五笔码
        {
            buttonpym.Text = buttonwbm.Text;
            buttonwbm.Visible = false;
            buttonpy.Visible = false;
            buttonjqcx.Visible = false;
        }

        private void buttonjqcx_Click(object sender, EventArgs e)//精确查询
        {
            buttonpym.Text = buttonjqcx.Text;
            buttonwbm.Visible = false;
            buttonpy.Visible = false;
            buttonjqcx.Visible = false;
        }

        private void button7_Click(object sender, EventArgs e)//拼音码 或 五笔码 或 精确查询 按钮 //使用正则表达式过滤非法输入
        {
            string pattern = @"[^]*\u4e00-\u9fa5^a-zA-Z]"; //匹配出纯汉字字母,不过滤*号，因为特殊药品是*打头的。可以过滤 . ' ！@#￥% &（）{}【】、|。?/\, =;@# ~ -+
            string inputstr = textBox1.Text.Trim();  
            Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);//pattern作为正则表达式的匹配模式
            string outputstr = rgx.Replace(inputstr, "");// "" 表示不用任何字符替换不合法的字符，直接过滤掉，返回合法字符(字母汉字，可以有*号)
            
            if (firsttime == 0)
            {
                firsttime = 1;
                getData();
            }

            if (textBox1.Text == " ")
            {
                if (ds1.Tables[0].DefaultView.Count != 0)//还没有经过过滤的全部数据
                {
                    dataGridViewpywb.Visible = true;//拼音，五笔，精确查询数据窗口
                    dataGridViewflcx.Visible = false;//树节点分类查询 数据窗口
                    dataGridViewmhcx.Visible = false; //模糊查询 数据窗口
                }
            }

            try
            {
                if (buttonpym.Text == buttonpy.Text)
                    ds1.Tables[0].DefaultView.RowFilter = " 拼音代码 like'" +outputstr+ "%'";//拼音码查询 过滤
                else if (buttonpym.Text == buttonwbm.Text)
                    ds1.Tables[0].DefaultView.RowFilter = " 五笔代码 like'" + outputstr + "%'";//五笔码查询 过滤
                else
                    ds1.Tables[0].DefaultView.RowFilter = " 药品名称 ='" + outputstr + "'";//
            }
            catch
            {    
            }
            
        
            if (ds1.Tables[0].DefaultView.Count != 0)
            {
                dataGridViewpywb.Visible = true;
                dataGridViewflcx.Visible = false;
                dataGridViewmhcx.Visible = false;
                dataGridViewpywb.CurrentCell = dataGridViewpywb[0, 0];
            }
        }

       

       //-------------------------------------------------------------------------------------------------------------

        public string[] getChaXunstr(string strtemp)//模糊查询要用的取查询字符串 
        {                                           //如输入框中输入厄沙坦//该方法将其切割成数组{厄，沙，坦}
            string[] key = new string[strtemp.Length];
            for (int i = 0; i < strtemp.Length; i++)
                key[i] = strtemp.Substring(i, 1);
            string[] ss = key;
            return key;
        }

        private void button6_Click(object sender, EventArgs e)//模糊查询按钮 //使用正则表达式过滤非法输入
        {
            string pattern = @"[^]*\u4e00-\u9fa5^a-zA-Z]"; //匹配出汉字字母，不过滤*号，因为特殊药品是*打头的。可以过滤 . ' ！@#￥% &*（）{}【】、|。?/\, =;@# ~ -+
            string inputstr = textBox3.Text.Trim();
            Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);//pattern作为正则表达式的匹配模式
            string outputstr = rgx.Replace(inputstr, "");// "" 表示不用任何字符替换不合法的字符，直接过滤掉，返回合法字符(字母汉字，可以有*号)

            SqlConnection cnn = new SqlConnection(SQLConnect.get());
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = cnn;
            string strsql = "select ypmc as '药品名称',ypgg as '药品规格',ypdw as '药品单位',jixing as '剂型',mzjl as '门诊剂量',jldw as '剂量单位',zxbz as '最小包装',zxdw as '最小单位',zxdj as '最小单价',pydm as '拼音代码',wbdm as '五笔代码',case tsyp when '0' then '普通' when '1' then '特殊' end as '特殊药品',case pishi when '0' then '否' when '1' then '是' end as '皮试',"+
            "case type when '1' then '西药' when '2' then '中药' end as '类型 ',case zfpb when '0' then '否' when '1' then '是' end as '作废',productor as '生产商' from typk where (ypmc like '%";
            string strkey = outputstr;
            string[] key = getChaXunstr(strkey);
            for (int i = 0; i < key.Length; i++)
            {
                strsql += key[i] + "%";          //如 pymc like % 厄 % 沙 % 坦 %
            }
            strsql += "')";
            cmd.CommandText = strsql;
            SqlDataAdapter adp = new SqlDataAdapter();
            adp.SelectCommand = cmd;
            DataSet ds = new DataSet();
            adp.Fill(ds);
            dataGridViewmhcx.DataSource=ds.Tables[0];
           
            dataGridViewmhcx.Visible = true;
            dataGridViewpywb.Visible = false;
            dataGridViewflcx.Visible = false;


        }


        //----------------------------------------------------------------------------------------------------------

        private void button6_Click_1(object sender, EventArgs e)//清空 按钮
        {
            textBox1.Text = "";
            textBox3.Text = "";
            dataGridViewpywb.Visible = false;
            dataGridViewmhcx.Visible = false;
            dataGridViewflcx.Visible = true;
        }

        private void buttonexit_Click(object sender, EventArgs e)//退出按钮
        {
            this.Close();
        }

        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                button7_Click(null,null);
        }

        private void textBox3_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                button6_Click(null, null);
        }

       

        


    }
}